<template>
  <a-modal
    class="invoice-info-modal"
    :visible="visible"
    :maskClosable="false"
    :destroyOnClose="true"
    :keyboard="false"
    :closable="false"
    @cancel="closeModal(false)"
    width="1200px"
  >
    <a-spin tip="Loading..." :spinning="tableLoading">
      <div
        class="title"
        :style="{
          color:
            checkValue && fileList.length == 0 ? 'red' : 'rgba(0, 0, 0, 0.65)',
        }"
      >
        <span>*</span>上传封面
      </div>
      <div class="imgList">
        <div
          class="imgItem bgImgItem"
          v-for="(item, index) in fileList"
          :key="index + 'id'"
          :style="{
            background: `url(${item.url}) no-repeat 50% 50% / cover`,
          }"
        >
          <div class="bgBanner">
            <div class="leftOpration">
              <a-icon
                type="left-circle"
                theme="filled"
                v-if="index > 0"
                @click="lastItem(item, index, fileList)"
              />
            </div>
            <div class="centerOpration">
              <a-icon type="eye" @click="handlePreview(item)" />
              <a-icon
                type="delete"
                @click="deleteItem(item, index, fileList)"
              />
            </div>
            <div class="rightOpration">
              <a-icon
                type="right-circle"
                theme="filled"
                v-if="index < fileList.length - 1"
                @click="nextItem(item, index, fileList)"
              />
            </div>
          </div>
        </div>
        <div class="imgItem">
          <a-upload
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :accept="accept"
            :disabled="disabled"
            :action="`${BASE_URL}/upload`"
            :show-upload-list="false"
            :before-upload="beforeUpload"
            @preview="handlePreview"
            @change="handleChange"
          >
            <div v-if="fileList.length < 9">
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传封面</div>
            </div>
          </a-upload>
          <a-modal
            :visible="previewVisible"
            :footer="null"
            @cancel="handleCancel"
          >
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </div>
      </div>
      <div
        :style="{
          margin: '-10px 0 20px 10px',
          color:
            checkValue && fileList.length == 0 ? 'red' : 'rgba(0, 0, 0, 0.65)',
        }"
      >
        请上传活动邀请卡，建议尺寸750*562，最多可上传9张
      </div>

      <div
        class="title mar10"
        :style="{
          color: checkValue && !formData.name ? 'red' : 'rgba(0, 0, 0, 0.65)',
        }"
      >
        <span>*</span>售卡名称
      </div>
      <div class="rule">
        <a-input
          :style="{
            width: '400px',
            border: checkValue && !formData.name ? '1px solid red' : '',
          }"
          placeholder="请填写活动名称，最多15个字"
          :max-length="15"
          v-model="formData.name"
        />
        <span class="limitWords" v-if="formData.name"
          >{{ formData.name.length || 0 }}/15</span
        >
        <span class="limitWords" v-else>0/15</span>
      </div>

      <div
        class="title mar10"
        :style="{
          color:
            checkValue &&
            (!formData.signUp || formData.signUp < formData.commission)
              ? 'red'
              : 'rgba(0, 0, 0, 0.65)',
        }"
      >
        <span>*</span>{{ formData.signUpAlias || "报名费用" }}
        <a-icon type="form" class="updateName" @click="openUpdateNameModel" />
      </div>
      <!-- <a-input
      style="width: 400px"
      placeholder="请填写报名费用"
      v-model="formData.signUp"
    /> -->
      <a-input-number
        :style="{
          width: '300px',
          border:
            checkValue &&
            (!formData.signUp || formData.signUp < formData.commission)
              ? '1px solid red'
              : '',
        }"
        :placeholder="`请填写${formData.signUpAlias || '报名费用'}（元）`"
        v-model="formData.signUp"
        :min="0.01"
        :step="1"
        :precision="2"
      />
      <a-modal
        :visible="updateNameVisible"
        @ok="handleOk"
        @cancel="closeUpdateName"
        title="修改文字"
        class="updateNameModel"
      >
        <div class="rule">
          <a-input
            style="width: 400px"
            placeholder="最多输入五个字"
            v-model="signUpAlias"
            :max-length="5"
          />
          <span class="limitWords" v-if="signUpAlias"
            >{{ signUpAlias.length || 0 }}/5</span
          >
          <span class="limitWords" v-else>0/5</span>
        </div>
      </a-modal>

      <div
        class="title mar10"
        :style="{
          color:
            checkValue &&
            (!formData.commission || formData.signUp < formData.commission)
              ? 'red'
              : 'rgba(0, 0, 0, 0.65)',
        }"
      >
        <span>*</span>活动佣金
      </div>
      <!-- <a-input style="width: 400px" placeholder="请填写活动佣金" /> -->
      <a-input-number
        :style="{
          width: '300px',
          border:
            checkValue &&
            (!formData.commission || formData.signUp < formData.commission)
              ? '1px solid red'
              : '',
        }"
        placeholder="请填写活动佣金（元）"
        v-model="formData.commission"
        :min="0.01"
        :step="1"
        :precision="2"
      />

      <div
        class="title mar10"
        :style="{
          color:
            checkValue && (!formData.signEndDate || dateCheck)
              ? 'red'
              : 'rgba(0, 0, 0, 0.65)',
        }"
      >
        <span>*</span>报名截止时间
      </div>
      <a-date-picker
        :style="{
          width: '400px',
          border:
            checkValue && (!formData.signEndDate || dateCheck)
              ? '1px solid red'
              : '',
        }"
        allow-clear
        :disabled-date="disabledStartDate"
        show-time
        format="YYYY-MM-DD HH:mm:ss"
        value-format="YYYY-MM-DD HH:mm:ss"
        placeholder="请选择报名截止时间"
        v-model="formData.signEndDate"
      />
      <div
        class="title mar10"
        :style="{
          color:
            checkValue && (!formData.activityEndDate || dateCheck)
              ? 'red'
              : 'rgba(0, 0, 0, 0.65)',
        }"
      >
        <span>*</span>活动截止时间
      </div>
      <a-date-picker
        :style="{
          width: '400px',
          border:
            checkValue && (!formData.activityEndDate || dateCheck)
              ? '1px solid red'
              : '',
        }"
        allow-clear
        :disabled-date="disabledStartDate"
        show-time
        format="YYYY-MM-DD HH:mm:ss"
        value-format="YYYY-MM-DD HH:mm:ss"
        placeholder="请选择活动截止时间"
        v-model="formData.activityEndDate"
      />
      <div class="title mar10">售卡数量</div>
      <a-input-number
        :min="0"
        :step="1"
        :precision="0"
        placeholder="请输入售卡数量"
        style="width: 300px"
        v-model="formData.amount"
      />

      <div class="title mar10">选择发布门店</div>
      <div
        class="shopInput"
        @click="openShoplistModel"
        :style="{
          color: shopIdList.length > 0 ? 'rgba(0, 0, 0, 0.65)' : '#d9d9d9',
        }"
      >
        {{
          shopIdList.length > 0
            ? `已选择 ${shopIdList.length} 个门店`
            : "请选择发布门店"
        }}
      </div>

      <div
        class="title mar10"
        :style="{
          color:
            checkValue && !formData.describtion ? 'red' : 'rgba(0, 0, 0, 0.65)',
        }"
      >
        <span>*</span>活动须知
      </div>
      <div class="rule">
        <a-textarea
          allow-clear
          :style="{
            width: '400px',
            border: checkValue && !formData.describtion ? '1px solid red' : '',
          }"
          :maxLength="200"
          :auto-size="{ minRows: 5, maxRows: 10 }"
          placeholder="请输入活动须知"
          v-model="formData.describtion"
        />
        <span class="limitWords" v-if="formData.describtion"
          >{{ formData.describtion.length || 0 }}/200</span
        >
        <span class="limitWords" v-else>0/200</span>
      </div>

      <!-- <div
        class="title mar10"
        :style="{
          color:
            checkValue && !formData.ruleImages ? 'red' : 'rgba(0, 0, 0, 0.65)',
        }"
      >
        <span>*</span>详细规则
      </div>
      <div style="width: 90%">
        <tinymce-editor
          v-model="formData.ruleImages"
          :style="{
            border: checkValue && !formData.ruleImages ? '1px solid red' : '',
          }"
        ></tinymce-editor>
      </div> -->

      <div
        class="title mar10"
        :style="{
          color:
            checkValue && ruleImages.length == 0
              ? 'red'
              : 'rgba(0, 0, 0, 0.65)',
        }"
      >
        <span>*</span>详细规则
      </div>
      <div class="imgList">
        <div
          class="imgItem bgImgItem"
          v-for="(item, index) in ruleImages"
          :key="index + 'id'"
          :style="{
            background: `url(${item.url}) no-repeat 50% 50% / cover`,
          }"
        >
          <div class="bgBanner">
            <div class="leftOpration">
              <a-icon
                type="left-circle"
                theme="filled"
                v-if="index > 0"
                @click="lastItem(item, index, ruleImages)"
              />
            </div>
            <div class="centerOpration">
              <a-icon type="eye" @click="handlePreview(item)" />
              <a-icon
                type="delete"
                @click="deleteItem(item, index, ruleImages)"
              />
            </div>
            <div class="rightOpration">
              <a-icon
                type="right-circle"
                theme="filled"
                v-if="index < fileList.length - 1"
                @click="nextItem(item, index, ruleImages)"
              />
            </div>
          </div>
        </div>
        <div class="imgItem">
          <a-upload
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :accept="accept"
            :disabled="ruleDisabled"
            :action="`${BASE_URL}/upload`"
            :show-upload-list="false"
            :before-upload="beforeUpload"
            @preview="handlePreview"
            @change="handleChangeRule"
          >
            <div v-if="ruleImages.length < 9">
              <a-icon :type="ruleLoading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">上传详细规则</div>
            </div>
          </a-upload>
          <a-modal
            :visible="previewVisible"
            :footer="null"
            @cancel="handleCancel"
          >
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </div>
      </div>
      <div
        :style="{
          margin: '-10px 0 20px 10px',
          color:
            checkValue && fileList.length == 0 ? 'red' : 'rgba(0, 0, 0, 0.65)',
        }"
      >
        请上传详细规则，建议尺寸750*562，最多可上传9张
      </div>
    </a-spin>
    <template slot="footer">
      <a-button key="back" @click="closeModal"> 取消 </a-button>
      <a-button
        key="submit"
        type="primary"
        @click="publish(1)"
        :loading="tableLoading"
        >保存</a-button
      >
      <a-button type="primary" @click="publish(2)" :loading="tableLoading">
        发布
      </a-button>
    </template>
    <shopList
      ref="shopList"
      @confirmGoodList="confirmGoodList"
      :shopIdList="shopIdList"
    ></shopList>
  </a-modal>
</template>
<script>
import { BASE_URL } from "@/axios/config";
import shopList from "./shopList.vue";
import moment from "moment";
export default {
  name: "addActivity",
  components: {
    shopList,
  },
  props: {
    visible: {
      // 是否显示弹窗
      type: Boolean,
      default: false,
    },
    opration: {
      type: String,
      default: "add",
    },
    activeId: {
      type: String,
      default: "",
    },
  },
  computed: {
    dateCheck() {
      if (this.formData.signEndDate && this.formData.activityEndDate) {
        const date1 = new Date(this.formData.signEndDate);
        const date2 = new Date(this.formData.activityEndDate);
        if (date1.getTime() > date2.getTime()) {
          return true;
        } else {
          return false;
        }
      }
    },
  },
  data() {
    return {
      accept: "image/gif,image/jpeg,image/png,image/jpg",
      BASE_URL,
      loading: false,
      ruleLoading: false,
      previewVisible: false,
      updateNameVisible: false,
      previewImage: "",
      fileList: [],
      disabled: false,
      ruleDisabled: false,
      formData: {},
      signUpAlias: "",
      shopIdList: [],
      checkValue: false,
      tableLoading: false,
      ruleImages: [],
    };
  },
  watch: {
    updateNameVisible(n) {
      if (n) {
        this.signUpAlias = this.formData.signUpAlias || "";
      }
    },
    previewVisible(p) {
      if (!p) {
        this.previewImage = "";
      }
    },
    visible(y) {
      if (y) {
        if (this.opration == "add") {
          this.formData = {};
          this.fileList = [];
          this.ruleImages = [];
          this.shopIdList = [];
          this.signUpAlias = "";
        } else {
          this.getActivityInfo({ id: this.activeId });
        }
      } else {
        this.formData = {};
        this.fileList = [];
        this.ruleImages = [];
        this.shopIdList = [];
        this.signUpAlias = "";
        this.checkValue = false;
        this.loading = false;
        this.ruleLoading = false;
        this.tableLoading = false;
        this.disabled = false;
        this.ruleDisabled = false;
      }
    },
  },
  methods: {
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("图片大于2M!");
      }
      return isLt2M;
    },
    handleChange({ file, fileList, e }) {
      if (file.status === "uploading") {
        this.loading = true;
        this.disabled = true;
        return;
      }
      if (file.status === "done") {
        console.log("status", file.status);
        console.log("file.response", file.response);
        // 上传接口返回失败
        if (file && file.response && file.response.returnCode !== 1000) {
          // this.fileList = fileList.filter(item => item.uid !== file.uid)
          this.$message.error(file.response.message);
          return false;
        } else {
          console.log("success file", file);
          console.log("success file", fileList);
          // this.imageUrl = file.response.dataInfo.url
          const imageUrl = file.response.dataInfo.url;
          this.fileList.push({
            uid: file.uid,
            name: file.name,
            status: file.status,
            url: imageUrl,
          });
          this.loading = false;
          this.disabled = false;
        }
      }
    },
    //处理详细规则
    handleChangeRule({ file, fileList, e }) {
      if (file.status === "uploading") {
        this.ruleLoading = true;
        this.ruleDisabled = true;
        return;
      }
      if (file.status === "done") {
        console.log("status", file.status);
        console.log("file.response", file.response);
        // 上传接口返回失败
        if (file && file.response && file.response.returnCode !== 1000) {
          // this.fileList = fileList.filter(item => item.uid !== file.uid)
          this.$message.error(file.response.message);
          return false;
        } else {
          console.log("success file", file);
          console.log("success file", fileList);
          // this.imageUrl = file.response.dataInfo.url
          const imageUrl = file.response.dataInfo.url;
          this.ruleImages.push({
            uid: file.uid,
            name: file.name,
            status: file.status,
            url: imageUrl,
          });
          this.ruleLoading = false;
          this.ruleDisabled = false;
        }
      }
    },
    handleCancel() {
      this.previewVisible = false;
    },
    handlePreview(file) {
      this.previewImage = file.url;
      this.previewVisible = true;
    },
    closeModal(bool) {
      this.$emit("cancel", bool);
    },
    closeUpdateName() {
      this.updateNameVisible = false;
    },
    handleOk() {
      this.formData.signUpAlias = this.signUpAlias;
      this.updateNameVisible = false;
    },
    openUpdateNameModel() {
      this.updateNameVisible = true;
    },
    lastItem(item, index, arr) {
      arr[index] = arr.splice(index - 1, 1, arr[index])[0];
    },
    nextItem(item, index, arr) {
      arr[index] = arr.splice(index + 1, 1, arr[index])[0];
    },
    deleteItem(item, index, arr) {
      arr.splice(index, 1);
    },
    // 开始时间不能小于当前时间
    disabledStartDate(current) {
      return current < moment().subtract(1, "days");
    },
    openShoplistModel() {
      this.$refs.shopList.visible = true;
    },
    confirmGoodList(e) {
      console.log(e);
      this.shopIdList = e;
    },

    //发布
    publish(status) {
      this.checkValue = true;
      let checkNum = 0;
      if (this.fileList.length == 0) checkNum++;
      if (!this.formData.name) checkNum++;
      if (!this.formData.signUp) checkNum++;
      if (!this.formData.commission) checkNum++;
      if (!this.formData.signEndDate) checkNum++;
      if (!this.formData.activityEndDate) checkNum++;
      if (!this.formData.describtion) checkNum++;
      // if (!this.formData.ruleImages) checkNum++;
      if (this.ruleImages.length == 0) checkNum++;
      if (checkNum > 0) {
        this.$message.error("必填项未填写");
      } else {
        let num = 0;
        if (this.dateCheck) {
          this.$message.error("报名截止时间不能大于活动截止时间");
          num++;
        }
        if (this.formData.signUp < this.formData.commission) {
          this.$message.error("活动佣金不能大于报名费用");
          num++;
        }
        if (num > 0) return;
        let params = JSON.parse(JSON.stringify(this.formData));
        let coverImages = "";
        this.fileList.forEach((item) => {
          coverImages = coverImages + item.url + ",";
        });
        coverImages = coverImages.substring(0, coverImages.length - 1);
        params.coverImages = coverImages;
        //详细规则
        let ruleImages = "";
        this.ruleImages.forEach((item) => {
          ruleImages = ruleImages + item.url + ",";
        });
        ruleImages = ruleImages.substring(0, ruleImages.length - 1);
        params.ruleImages = ruleImages;

        params.signUpAlias = this.signUpAlias;
        let ids = "";
        this.shopIdList.forEach((item) => {
          ids = ids + item + ",";
        });
        ids = ids.substring(0, ids.length - 1);
        params.releaseShopId = ids;

        params.status = status;

        params.commission = params.commission * 10 * 10;
        params.signUp = params.signUp * 10 * 10;
        // console.log(params, "00000000000000000000");
        if (this.opration == "add") {
          this.addCardActivity(params);
        } else {
          params.id = this.activeId;
          this.updateCardActivity(params);
        }
      }
    },

    //新增售卡活动
    async addCardActivity(params) {
      let res = await this.$post("sale/card/add", params);
      if (res && res.returnCode == 1000) {
        this.$message.success("创建售卡活动成功");
        this.$emit("freshTable");
        this.$emit("cancel", false);
      }
    },

    //更新售卡活动
    async updateCardActivity(params) {
      let res = await this.$post("sale/card/update", params);
      if (res && res.returnCode == 1000) {
        this.$message.success("编辑售卡活动成功");
        this.$emit("freshTable");
        this.$emit("cancel", false);
      }
    },

    //获取活动详情
    async getActivityInfo(params) {
      this.tableLoading = true;
      let res = await this.$get("sale/card/id", params);
      if (res && res.returnCode == 1000) {
        this.fileList = res.dataInfo.coverImages
          .split(",")
          .map((item, index) => {
            return {
              uid: index,
              name: item,
              status: "done",
              url: item,
            };
          });

        this.ruleImages = res.dataInfo.ruleImages
          .split(",")
          .map((item, index) => {
            return {
              uid: index,
              name: item,
              status: "done",
              url: item,
            };
          });
        this.shopIdList = res.dataInfo.releaseShopList.map((item) => {
          return item.shopId;
        });
        this.signUpAlias = res.dataInfo.signUpAlias;
        this.formData = {
          name: res.dataInfo.name,
          signUp: ((res.dataInfo.signUp * 1) / 100).toFixed(2),
          commission: ((res.dataInfo.commission * 1) / 100).toFixed(2),
          signEndDate: res.dataInfo.signEndDate,
          activityEndDate: res.dataInfo.activityEndDate,
          amount: res.dataInfo.amount,
          describtion: res.dataInfo.describtion,
          // ruleImages: res.dataInfo.ruleImages,
        };
        this.tableLoading = false;
      } else {
        this.tableLoading = false;
      }
    },
  },
};
</script>
<style lang="less" scoped>
.mar10 {
  margin-top: 15px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.title {
  font-size: 16px;
  margin-bottom: 10px;
  span {
    color: red;
  }
}
.imgList {
  width: 100%;
  display: grid;
  flex-wrap: wrap;
  grid-template-columns: repeat(7, 1fr);
  justify-items: center;
  align-items: center;
  // justify-content: space-between;
  .imgItem {
    width: 133px;
    height: 100px;
    margin-bottom: 20px;
    position: relative;
  }
}
/deep/ .ant-upload.ant-upload-select-picture-card {
  width: 100%;
  height: 100px;
}
.bgBanner {
  position: absolute;
  z-index: 1;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: all 0.3s;
  content: " ";
  .centerOpration {
    width: 40%;
    position: absolute;
    height: 100%;
    left: 30%;
    display: flex;
    align-items: center;
    justify-content: space-around;
    color: white;
    font-size: 16px;
  }
  .leftOpration {
    width: 20%;
    position: absolute;
    height: 100%;
    left: 7px;
    display: flex;
    align-items: center;
    color: yellow;
    font-size: 16px;
  }
  .rightOpration {
    width: 20%;
    position: absolute;
    height: 100%;
    right: 7px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    color: yellow;
    font-size: 16px;
  }
}
.bgImgItem:hover {
  .bgBanner {
    opacity: 1;
    cursor: pointer;
  }
}
/deep/.ant-modal-footer {
  display: flex;
  justify-content: center;
}
/deep/.ant-modal-footer button + button {
  margin-left: 30px;
}
.updateName {
  font-size: 14px;
  color: #9fe59f;
  cursor: pointer;
}
.updateNameModel {
  /deep/.ant-modal-body {
    display: flex;
    justify-content: center;
  }
}
.rule {
  position: relative;
  width: 400px;
  .limitWords {
    position: absolute;
    right: 6px;
    bottom: 4px;
    font-size: 10px;
    color: #ccc;
  }
}
.shopInput {
  width: 400px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  line-height: 1.5;
  height: 32px;
  padding: 4px 11px;
  // color: rgba(0, 0, 0, 0.65);
  color: #d9d9d9;
  font-size: 14px;
  cursor: text;
}
</style>